<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 15:22:10
 * @LastEditTime: 2023-09-02 12:21:26
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 兼容老接口数据
 */

namespace App\Http\Controllers\OldController;

use App\Repositories\TemporaryTokenRepository;
use App\Repositories\UserRepository;
use Laravel\Lumen\Routing\Controller as BaseController;
use EasyWeChat\MiniApp\Application as MiniApp;
use Illuminate\Support\Facades\Hash;

/**
 * 老系统兼容接口
 * @property UserRepository $user 
 * @property TemporaryTokenRepository $T_token 
 * @author sunkaiyuan
 */
class MiniProLoginController extends BaseController
    {

    public function __construct(
        UserRepository $user,
        TemporaryTokenRepository $T_token
    ) {
        $this->user    = $user;
        $this->T_token = $T_token;
        }

    public function autologin()
        {
        $request      = request();
        $MiniApp      = app()->MiniApp;
        $openid       = $MiniApp->getUtils()->codeToSession(request("code"));
        $user         = $this->user->whereOpenid($openid['openid'])->first();
        $loginsession = $this->T_token->createToken($user->employee_id, "wx", $request->ip())['token'];

        if ($user)
            return [...$user->toArray(), 'loginsession' => $loginsession];
        else
            fail("登录失败，或者授权过期，请重新登录！", 401, ['openid' => $openid['openid']]);
        }
    public function login()
        {
        $request  = request();
        $username = $request->username;
        $password = $request->password;
        $openid   = $request->openid;
        // 查询帐号 

        $user = $this->user->whereUsername($username)->getOne();

        if (!$user || !Hash::check($password, $user->password)) {
            fail('用户名或密码不正确,登录失败');
            }
        //生成登录token 
        $loginsession = $this->T_token->createToken($user->employee_id, "wx", $request->ip())['token'];

        $user->openid = $openid;
        $user->save();
        return [...$user->toArray(), 'loginsession' => $loginsession];
        }
    }